package org.Date;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TestCalendar {
    public static void setTime() {
        //采用单例模式获取日历对象Calendar.getInstance();
        Calendar c = Calendar.getInstance();

        //通过日历对象得到日期对象
        Date d = c.getTime();

        System.out.println("current date: " + d.toString());

        Date d2 = new Date(0);
        c.setTime(d2); //把这个日历，调成日期 : 1970.1.1 08:00:00

        System.out.println("set Date: " + c.getTime().toString());
    }

    public static void turnCalendar() {
        Calendar c = Calendar.getInstance();
        Date now = c.getTime();
        // 当前日期
        System.out.println("当前日期：\t" + format(c.getTime()));

        // 下个月的今天
        c.setTime(now);
        c.add(Calendar.MONTH, 1);
        System.out.println("下个月的今天:\t" +format(c.getTime()));

        // 去年的今天
        c.setTime(now);
        c.add(Calendar.YEAR, -1);
        System.out.println("去年的今天:\t" +format(c.getTime()));

        // 上个月的第三天
        c.setTime(now);
        c.add(Calendar.MONTH, -1);
        c.set(Calendar.DATE, 3);
        System.out.println("上个月的第三天:\t" +format(c.getTime()));
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static String format(Date time) {
        return sdf.format(time);
    }
    public static void find3rdLastDayOfNextMonth(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        String nowDateStr = format(date);
        int nowDay = Integer.parseInt(nowDateStr.substring(8,10));

        c.add(Calendar.MONTH, 1); // 下个月
        int dayOfMonth = c.getMaximum(Calendar.DAY_OF_MONTH);
//        System.out.println("current day of month: " + dayOfMonth);
        c.add(Calendar.DATE, dayOfMonth - 2 - nowDay);
        c.set(Calendar.DATE, dayOfMonth - 2);
        System.out.println("今天是: " + date.toString());
        System.out.println("下个月倒数第三天" + c.getTime().toString());
    }
}
